package mi.payment.utils.transaction;

import android.content.Context;
import android.util.Log;

import java.util.Map;
import java.util.Properties;

import mi.payment.utils.Config;
import mi.payment.utils.iso8583.MsgField;
import sunmi.sunmiui.utils.LogUtil;

/**
 * IC卡参数下载(AID下载)
 *
 * @author tomcat on 2017/2/17.
 */
public class ICParamsDownloadTask extends TransactionTask<Void, Void, String> {

    private static final String TAG = "ICParamsDownloadTask";

    protected ICParamsDownloadTask(Context c) {
        super(c, false);
    }

    @Override
    protected void onBegin(Void[] params) {
    }

    @Override
    protected String appointResult() {
        return null;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return null;
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        return null;
    }

    @Override
    protected String doTransactionSelf() {
        POSStatusUpload aidSeekTask = new POSStatusUpload(context);
        ParamsDownloadTask aidDownloadTask = new ParamsDownloadTask(context);

        resultStr = "FF";
        // 获取所有aid tag
        String aids = "";
        int aidSize = 0;
        Properties prop = new Properties();

        while (true) {
            String aidTags = aidSeekTask.syncExecute("392", String.valueOf(100 + aidSize));
            if (aidTags != null && aidTags.length() > 2) {
                LogUtil.e(TAG, "aid_tag: " + aidTags);
                aids += aidTags.substring(2);
                if (aidTags.substring(0, 2).equals("30") || aidTags.substring(0, 2).equals("31") || aidTags.substring(0, 2).equals("33")) {
                    break;
                }
                String[] AIDS = aids.split("9F06");
                aidSize = AIDS.length - 1;
            } else {
                return resultStr;
            }
        }
        LogUtil.e(TAG, "aid_tag_list: " + aids);

        // 下载AID并保存
        while (true) {

            if (aids.length() < 8) {
                break;
            }

            // AID[9F06]
            int index9F06 = aids.indexOf("9F06", 4);

            String ret;
            String tAid = "";
            String[] params = new String[]{"390", tAid};

            if (index9F06 > 0) {
                tAid = aids.substring(0, index9F06);
                aids = aids.substring(index9F06);
                params[1] = tAid;
                ret = aidDownloadTask.syncExecute(params);
            } else if (aids.length() > 0) {
                tAid = aids;
                aids = "";
                params[1] = tAid;
                ret = aidDownloadTask.syncExecute(params);
            } else {
                break;
            }

            LogUtil.e(TAG, "aid_response: " + ret);

            prop.setProperty(tAid, ret.substring(2).toUpperCase());

            resultStr = ret;
        }

        if (!prop.isEmpty()) {
            Config.saveAIDs(prop);
        }

        return resultStr;
    }


}
